import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
import json
import time


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "癌症医疗保险"

    # 生产产品信息
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(0, 51)],
            # 性别
            "gender": ["M", "F"],
            # 保障期限
            "expire": ["1年"],
            # 交费类型
            "payType": ["年交"],
            # 保额
            "money": ["50000", "100000", "200000"]
        }
        for v in product(plan["year"], plan["gender"], plan["expire"], plan["payType"], plan["money"]):
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3], v[4]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(
                v[0], v[1], v[2], v[3], v[4]
            ))

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["gender"] == "M":

            sex = {
                "man":"1",
                "women":"0"
            }
        else:
            sex = {
                "man": "0",
                "women": "1"
            }

        data = {"from": "ald", "beginDate": "2020-03-13", "birthDate": "{0}-01-01".format( str(2020-int(dt["year"]))), "insurantManNum": sex["man"],
                "insurantWomanNum": sex["women"], "planClass": 2,
                "amountFormList": [{"cancerDisease": 50000}, {"cancerDisease": 100000}, {"cancerDisease": dt["money"]}]}

        payload = json.dumps( data )
        r = requests.post( url =domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200:
            if dt["money"] == "50000":
                price = r.json()["quoteResult1"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print( data )
                self.mysql.updatePrice( data )
            elif dt["money"] == "100000":
                price = r.json()["quoteResult2"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print( data )
                self.mysql.updatePrice( data )
            else:
                price = r.json()["quoteResult3"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                print( data )
                self.mysql.updatePrice( data )

    def main(self):

        while True:

            dt = self.mysql.randTask( self.name )
            time.sleep(1)

            if not dt:

                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
